'use strict';
const Service = require('egg').Service;

class UserService extends Service {

  /**
   * 用户登录
   * @param data
   * @returns {Promise<{msg, code, data}>}
   */
  async login(data) {
    const { ctx } = this;
    try {
      // 查询
      const res = await this.findByUsername(data.username);
      if (res && res.password === ctx.helper.utils.passwordToBase64(data.password)) {
        // 生成Token
        const token = this.app.jwt.sign({
          username: data.username,
          password: data.password,
          userid: res.id,
        }, this.app.config.jwt.secret);
        // 链接Redis
        const redisConn = this.app.redis.getConn();
        const key = 'userid_' + res.id;
        // 存取
        await this.app.redis.set(redisConn, key, token);
        await this.app.redis.get(redisConn, key);
        // 设置过期的时间为半天
        await this.app.redis.expire(redisConn, key, 60 * 60 * 12);
        // 释放链接
        this.app.redis.doRelease(redisConn);
        return ctx.helper.utils.responseReturn(1, '登录成功', Object.assign({ token }, res.dataValues));
      }
      return ctx.helper.utils.responseReturn(-1, '信息有误');
    } catch (err) {
      return ctx.helper.utils.responseReturn(-1, '查询失败');
    }
  }

  /**
   * 新建用户
   * @param data
   * @returns {data}
   */
  create(data) {
    data.create_time = new Date();
    data.password = this.ctx.helper.utils.passwordToBase64(data.password);
    return this.app.model.User.create(data);
  }

  /**
   * 用户列表
   * @param offset
   * @param limit
   * @returns {Promise<*>}
   */
  async list({ offset = 0, limit = 10 }) {
    return this.app.model.User.findAndCountAll({
      offset,
      limit,
      order: [['create_time', 'desc'], ['id', 'desc']],
    });
  }

  /**
   * 查询
   * @param id
   * @returns {Promise<*>}
   */
  async find(id) {
    const user = await this.app.model.User.findByPk(id);
    if (!user) {
      this.ctx.throw(404, 'user not found');
    }
    return user;
  }

  /**
   * 按username字段进行搜索
   * @param username
   * @returns {*}
   */
  findByUsername(username) {
    return this.app.model.User.findOne({
      where: {
        username,
      },
    });
  }
  /**
   * 更新
   * @param id
   * @param updates
   * @returns {Promise<*>}
   */
  async update({ id, updates }) {
    const user = await this.app.model.User.findByPk(id);
    if (!user) {
      this.ctx.throw(404, 'user not found');
    }
    return user.update(updates);
  }

  /**
   * 删除
   * @param id
   * @returns {Promise<*>}
   */
  async del(id) {
    const user = await this.app.model.User.findByPk(id);
    if (!user) {
      this.ctx.throw(404, 'user not found');
    }
    return user.destroy();
  }

}

module.exports = UserService;
